# -*- coding: utf-8 -*-
from datetime import timedelta
import json

from django.views.decorators.http import require_GET

from common.pay.db import (
    list_pay, get_pay_overview, USER_TYPE, PAY_TYPE_TEXT, USER_TYPE_TEXT)
from common.utils.decorator import response_wrapper
from common.pay.model import PAY_STATUS
from common.utils.tz import utc_to_local_str, utc_to_local, get_utc_date
from common.utils.api import token_required
from common.utils.export import redirect_to_file, gen_filename
from common.lottery import LOTTERY_TYPE


@require_GET
@response_wrapper
@token_required
def get_pay_list(req):
    query_dct = req.GET.dict()
    return get_pay(query_dct)


@require_GET
@response_wrapper
@token_required
def get_pay_list_by_user_id(req):
    query_dct = req.GET.dict()
    if 'user_id' in query_dct:
        return get_pay(query_dct)
    return {}


def get_pay(query_dct):
    # only need finished pay
    is_fresh = query_dct.get('is_fresh', False)
    if is_fresh and int(is_fresh) and 'created_at' not in query_dct and 'updated_at' not in query_dct:
        today = get_utc_date() + timedelta(hours=8)
        query_dct['created_at'] = json.dumps({"$gte": str(today)})
    if 'status' not in query_dct:
        query_dct['status'] = '2'
    elif int(query_dct['status']) == 0:
        query_dct['status'] = json.dumps({'$in': [PAY_STATUS.SUBMIT, PAY_STATUS.DONE, PAY_STATUS.FAIL]})
    export = query_dct.pop('$export', None)
    if export:
        filename = gen_filename('pay')
        header = ['id', 'created_at', 'user_id', 'user_type',
                  'pay_type', 'price', 'activity_name']
        cn_header = ['id', u'创建时间', u'用户ID', u'用户类型', u'充值类型', u'充值总额',
                     u'购买/充值']
    items, total_count = list_pay(query_dct)
    resp_items = []
    for item in items:
        # item: Pay, Account.created_at
        pay, user_created_at = item
        data = pay.as_dict()
        data['id'] = str(data['id']) + ' '
        if user_created_at:
            pay_at = utc_to_local(pay.created_at).date()
            registered_at = utc_to_local(user_created_at).date()
            if pay_at == registered_at:
                data['user_type'] = USER_TYPE['new_user']
            elif ((pay_at - registered_at) >= timedelta(days=1)) and ((pay_at - registered_at) <= timedelta(days=2)):
                data['user_type'] = USER_TYPE['next_day_user']
            elif ((pay_at - registered_at) > timedelta(days=2)) and ((pay_at - registered_at) <= timedelta(days=6)):
                data['user_type'] = USER_TYPE['week_user']
            else:
                data['user_type'] = USER_TYPE['old_user']
        if export:
            data['user_type'] = USER_TYPE_TEXT[str(data['user_type'])]
            data['pay_type'] = PAY_TYPE_TEXT[str(data['pay_type'])]
        data['created_at'] = utc_to_local_str(data['created_at'])
        data['updated_at'] = utc_to_local_str(data['updated_at'])

        try:
            extend = json.loads(data.extend)
            activity_type = extend['buy_list'][0]['activity_type']
            activity_name = LOTTERY_TYPE.get_key(activity_type)
            data['activity_name'] = activity_name
        except:
            data['activity_name'] = '-'
        if export:
            resp_items.append([data.get(x, '-') for x in header])
        else:
            resp_items.append(data)

    if export:
        resp_items = reversed(resp_items)
        return redirect_to_file(resp_items, cn_header, filename)

    overview = get_pay_overview(query_dct)
    return {'list': resp_items, 'page': query_dct.get('$page', 1),
            'size': len(resp_items), 'total_count': total_count,
            'overview': overview}
